package com.wetool.jpa;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.wetool.entity.Merchant;
import com.wetool.entity.Shop;
import com.wetool.model.SearchParam;

/**
 * 描述：店铺自定义查询
 * 
 * @author lesim
 * @since 1.0
 */
public class ShopSpec implements Specification<Shop> {

	private final SearchParam param;

	public ShopSpec(SearchParam param) {
		this.param = param;
	}

	@Override
	public Predicate toPredicate(Root<Shop> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		List<Predicate> predicates = new ArrayList<>();
		// like 关键字
		if (StringUtils.isNotBlank(param.getKey())) {
			Predicate pred = cb.or(cb.like(cb.lower(root.get("name")), "%" + param.getKey().toLowerCase() + "%"));
			pred = cb.or(pred, cb.like(cb.lower(root.get("mobile")), "%" + param.getKey().toLowerCase() + "%"));
			predicates.add(pred);
		}
		// 子表查询 地区编号
		if (StringUtils.isNotEmpty(param.getAreaId())) {
			predicates.add(cb.like(root.get("area").get("areaIds"), "%" + param.getAreaId().toLowerCase() + "%"));
		}
		// 子表查询 商家id
		if (param.getMerchantId() != null) {
			predicates.add(cb.equal(root.get("merchant").get("id"), param.getMerchantId()));
		}
		
		/* 服务商id 查询所属店铺id */
		if (param.getSpId() != null) {
			Join<Merchant, Shop> join = root.join("merchant",JoinType.INNER);
			predicates.add(cb.equal(join.get("spId"), param.getSpId()));
		}
		// 日期格式大于
		if (param.getFrom() != null) {
			predicates.add(cb.greaterThan(root.get("createDate"), param.getFrom()));
		}
		if (param.getTo() != null) {
			predicates.add(cb.lessThan(root.get("createDate"), param.getTo()));
		}
		predicates.add(cb.notEqual( root.get("isDeleted"), 1)); 
		query.orderBy(cb.desc(root.get("createDate")));
		return andTogether(predicates, cb);
	}

	private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
		return cb.and(predicates.toArray(new Predicate[0]));
	}
}